<?php

namespace lib;

use think\facade\Cache;

class Liyang
{
    // Legacy API credentials
    private static $appkey = '810667ee4d544e9f';
    private static $appsecret = '698b607d611f4a0fab245dc628b70206';
    
    // VIN 2.0 API credentials
    private static $username = 'xinyaoan'; // 力洋提供的用户名
    private static $password = 'level1027*xinyaoan'; // 力洋提供的密码
    private static $baseUrl = 'http://api.levelvin.net/prod-api';
    
    // 缓存标识名
    private static $tokenCacheKey = 'liyang_api_token';

    /**
     * 获取API访问令牌
     * @return array
     */
    public static function getToken()
    {
        // 从缓存中获取token
        $token = Cache::get(self::$tokenCacheKey);
        if (!empty($token)) {
            return ['code' => 1, 'msg' => '获取成功', 'data' => $token];
        }

        $url = self::$baseUrl . '/gettoken';
        $data = [
            'username' => self::$username,
            'password' => self::$password
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $result = curl_exec($ch);
        
        if(curl_errno($ch)) {
            return ['code' => 0, 'msg' => '请求失败: ' . curl_error($ch)];
        }
        
        curl_close($ch);
        
        $response = json_decode($result, true);
        
        if (isset($response['code']) && $response['code'] == 200) {
            $token = $response['data'];
            // 将token存入缓存，有效期23小时
            Cache::set(self::$tokenCacheKey, $token, 23 * 3600);
            return ['code' => 1, 'msg' => '获取成功', 'data' => $token];
        }
        
        return ['code' => 0, 'msg' => '获取token失败', 'data' => $response];
    }

    /**
     * OCR识别VIN码（旧版API）
     * @param string $imgbase64
     * @return array
     */
    public static function getvinbyocr($imgbase64)
    {
        $data = [
            'imgbase64' => $imgbase64
        ];
        $url = 'https://interface.dat881.com/api/vin/getvinbyocr';
        return self::curl($url, $data);
    }
    
    /**
     * 普通API（包年）
     * @param string $vin 17位VIN码
     * @return array
     */
    public static function getNormalVin($vin)
    {
        return self::requestVinApi('/vinparse/normal6558', ['vin' => $vin]);
    }
    
    /**
     * 精准API（计次）
     * @param string $vin 17位VIN码
     * @return array
     */
    public static function getPreciseVin($vin)
    {
        return self::requestVinApi('/vinparse/precise4850', ['vin' => $vin]);
    }
    
    /**
     * 港澳API（包年）
     * @param string $vin VIN码
     * @return array
     */
    public static function getHongKongVin($vin)
    {
        return self::requestVinApi('/vinparse/hongkong_levelid', ['vin' => $vin]);
    }
    
    /**
     * VIN码纠错API（计次）
     * @param string $vin 17位VIN码
     * @return array
     */
    public static function checkErrorVin($vin)
    {
        return self::requestVinApi('/vinparse/checkerror', ['vin' => $vin]);
    }
    
    /**
     * 精准压缩API（计次）
     * @param string $cate 压缩ID类型，可选值：cid、did、gid、pid
     * @param string $vin 17位VIN码
     * @return array
     */
    public static function getPreciseCompressVin($vin)
    {
        return self::requestVinApi('/vinparse/precompressid', ['cate' => 'pid', 'vin' => $vin]);
    }
    
    /**
     * 车牌解析VIN（计次）
     * @param string $base64chepai Base64编码的车牌
     * @return array
     */
    public static function getLicenseVin($base64chepai)
    {
        return self::requestVinApi('/vinparse/chepaivin', ['base64chepai' => $base64chepai]);
    }
    
    /**
     * 款型API（计次）
     * @param string $vin 17位VIN码
     * @return array
     */
    public static function getSalesVersionVin($vin)
    {
        return self::requestVinApi('/vinparse/salesversion', ['vin' => $vin]);
    }
    
    /**
     * 精准API（包年）
     * @param string $vin 17位VIN码
     * @return array
     */
    public static function getPreciseVinYearly($vin)
    {
        return self::requestVinApi('/vinparse/precise4850_bn', ['vin' => $vin]);
    }
    
    /**
     * 普通压缩API（包年）
     * @param string $cate 压缩ID类型，可选值：cid、did、gid、pid
     * @param string $vin 17位VIN码
     * @return array
     */
    public static function getNormalCompressVinYearly($cate, $vin)
    {
        return self::requestVinApi('/vinparse/precompressid_bn', ['cate' => $cate, 'vin' => $vin]);
    }
    
    /**
     * VIN码纠错API（包年）
     * @param string $vin 17位VIN码
     * @return array
     */
    public static function checkErrorVinYearly($vin)
    {
        return self::requestVinApi('/vinparse/checkerror_bn', ['vin' => $vin]);
    }
    
    /**
     * 普通压缩API（计次）
     * @param string $cate 压缩ID类型，可选值：cid、did、gid、pid
     * @param string $vin 17位VIN码
     * @return array
     */
    public static function getNormalCompressVin($cate, $vin)
    {
        return self::requestVinApi('/vinparse/precompressid_pt', ['cate' => $cate, 'vin' => $vin]);
    }
    
    /**
     * 普通API（计次）
     * @param string $vin 17位VIN码
     * @return array
     */
    public static function getNormalVinPayPerUse($vin)
    {
        return self::requestVinApi('/vinparse/normal6558_jc', ['vin' => $vin]);
    }
    
    /**
     * 向力洋VIN 2.0 API发送请求
     * @param string $endpoint API端点
     * @param array $params 请求参数
     * @return array
     */
    private static function requestVinApi($endpoint, $params)
    {
        // 获取token
        $tokenResult = self::getToken();
        if ($tokenResult['code'] != 1) {
            return $tokenResult;
        }
        
        $token = $tokenResult['data'];
        $url = self::$baseUrl . $endpoint;
        
        // 构建查询字符串
        $queryString = http_build_query($params);
        $url = $url . '?' . $queryString;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, '');  // 空POST内容，参数已在URL中
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $token
        ]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $result = curl_exec($ch);
        
        if (curl_errno($ch)) {
            return ['code' => 0, 'msg' => '请求失败: ' . curl_error($ch)];
        }
        
        curl_close($ch);
        
        $response = json_decode($result, true);
        
        // 处理token失效的情况
        if (isset($response['code']) && $response['code'] == 401) {
            // 清除token缓存
            Cache::delete(self::$tokenCacheKey);
            
            // 重新获取token并重试
            $tokenResult = self::getToken();
            if ($tokenResult['code'] != 1) {
                return $tokenResult;
            }
            
            return self::requestVinApi($endpoint, $params);
        }
        
        if (isset($response['code']) && $response['code'] == 200) {
            return ['code' => 1, 'msg' => '请求成功', 'data' => $response['data']];
        }
        
        return ['code' => 0, 'msg' => isset($response['msg']) ? $response['msg'] : '请求失败', 'data' => $response];
    }
    
    /**
     * 向旧版API发送请求
     * @param string $url API地址
     * @param array $data 请求数据
     * @return array
     */
    private static function curl($url, $data)
    {
        $baseData = [
            'appkey' => self::$appkey,
            'appsecret' => self::$appsecret
        ];
        // 构建请求JSON
        $jsonInput = json_encode(array_merge($baseData, $data));

        // 初始化CURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ['jsonInput' => $jsonInput]);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // 执行请求
        $result = curl_exec($ch);

        // 检查是否有错误发生
        if(curl_errno($ch)) {
            return['code' => 0, 'msg'=>'请求失败: ' . curl_error($ch)];
        }

        curl_close($ch);

        // 解析返回结果
        return ['code' => 1, 'msg'=>'请求成功', 'data'=>json_decode($result, true)];
    }
}